"use client";
import { useEffect, useState } from "react";
import { useConversation } from "@/context/conversationContext";
import { Plus, Loader2 } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { ConversationItem } from "./item";
import { toast } from "sonner";
import { get, post } from "@/lib/request";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";

// 主列表
export default function ConversationList() {
  const { conversations, fetchConversations, currentConversation, setCurrentConversation } = useConversation();
  const [loading, setLoading] = useState(true);
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [allFriends, setAllFriends] = useState<{id:string,username:string,avatar:string|null}[]>([]);
  const [groupName, setGroupName] = useState('');
  const [selected, setSelected] = useState<string[]>([]);
  const [creating, setCreating] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetchConversations().finally(() => setLoading(false));
  }, [fetchConversations]);

  useEffect(() => {
    if (createDialogOpen) fetchFriends();
  }, [createDialogOpen]);

  async function fetchFriends() {
    try {
      const res = await get('/friends/list');
      if (res.data) {
        setAllFriends(res.data);
      }
    } catch {
      toast.error('获取好友列表失败');
    }
  }

  async function handleCreateGroup(e: React.FormEvent) {
    e.preventDefault();
    if (!groupName.trim() || selected.length === 0) return;
    setCreating(true);
    try {
      const res = await post('/groups', { name: groupName.trim(), members: selected });
      const newConversation = res.data;
      if (!newConversation) throw new Error('创建失败');
      toast.success('群聊创建成功！');
      setCreateDialogOpen(false);
      setGroupName('');
      setSelected([]);
      await fetchConversations();

      const conversationToSet = conversations.find(c => c.id === newConversation.id) || newConversation;
      setCurrentConversation(conversationToSet);

    } catch (e: any) {
      toast.error(e.message);
    } finally {
      setCreating(false);
    }
  }

  return (
    <div className="h-full flex flex-col">
      <header className="p-4 font-bold text-lg border-b flex items-center justify-between">
        <span>消息</span>
        <button
          className="ml-2 p-1 rounded hover:bg-gray-200 dark:hover:bg-stone-700"
          onClick={() => setCreateDialogOpen(true)}
          title="发起群聊"
        >
          <Plus size={20} />
        </button>
      </header>
      <div className="flex-1 overflow-y-auto">
        {loading ? (
          <div className="flex flex-col items-center justify-center h-full text-gray-400">
            <Loader2 className="animate-spin mb-2" /> 加载中...
          </div>
        ) : conversations.length === 0 ? (
          <div className="h-full flex flex-col items-center justify-center text-gray-400 select-none py-12">
            <svg width="64" height="64" fill="none" viewBox="0 0 24 24" stroke="currentColor" className="mb-4">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M21 15.5a2.5 2.5 0 01-2.5 2.5H7l-4 4V6.5A2.5 2.5 0 015.5 4h13A2.5 2.5 0 0121 6.5v9z" />
            </svg>
            <div className="text-lg font-medium">暂无消息</div>
            <div className="text-sm mt-1">快去添加好友，开启你的第一条对话吧！</div>
          </div>
        ) : (
          conversations.map(conv => (
            <ConversationItem
              key={conv.id}
              conversation={conv}
              selected={currentConversation?.id === conv.id}
              onClick={() => setCurrentConversation(conv)}
            />
          ))
        )}
      </div>
      {/* 建群 Dialog */}
      <Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>发起群聊</DialogTitle>
          </DialogHeader>
          <form onSubmit={handleCreateGroup}>
            <input
              className="w-full border rounded px-3 py-2 text-sm focus:ring-2 focus:ring-blue-200 outline-none dark:bg-slate-200 dark:text-slate-900"
              placeholder="请输入群聊名称"
              value={groupName}
              onChange={e => setGroupName(e.target.value)}
              disabled={creating}
              required
            />
            <div className="max-h-48 overflow-auto border rounded p-2 bg-gray-50 my-3">
              {allFriends.length === 0 ? (
                <div className="text-gray-400 text-sm">暂无可选好友</div>
              ) : (
                allFriends.map(f => (
                  <label key={f.id} className="flex items-center mb-1 cursor-pointer">
                    <input
                      type="checkbox"
                      className="mr-2"
                      checked={selected.includes(f.id)}
                      onChange={e => {
                        if (e.target.checked) setSelected(sel => [...sel, f.id]);
                        else setSelected(sel => sel.filter(id => id !== f.id));
                      }}
                      disabled={creating}
                    />
                    <Avatar className="h-6 w-6">
                      <AvatarImage src={f.avatar || undefined} alt={f.username} />
                      <AvatarFallback>{f.username.charAt(0).toUpperCase()}</AvatarFallback>
                    </Avatar>
                    <span className="ml-2">{f.username}</span>
                  </label>
                ))
              )}
            </div>
            <DialogFooter>
              <button
                type="button"
                className="px-4 py-2 rounded bg-gray-100 hover:bg-gray-200 mr-2"
                onClick={() => setCreateDialogOpen(false)}
                disabled={creating}
              >取消</button>
              <button
                type="submit"
                className="px-4 py-2 rounded bg-blue-500 text-white hover:bg-blue-600"
                disabled={creating || !groupName.trim() || selected.length === 0}
              >{creating ? '创建中...' : '创建'}</button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
} 